<template>
  <div class="culture-theme">
    <el-row class="CultureInfoDetail" justify="center" style="align-items: flex-start" type="flex">
      <el-col :span="24" class="CultureInfoDetail-left">
        <el-row class="CultureInfoDetail-left-title" justify="center" type="flex">
          <img alt="" src="@/assets/image/详情.png">
          <span>非遗项目详细信息</span>
        </el-row>
        <img alt="" class="bookmark" src="@/assets/image/书签.png" style="position: absolute;left: -2%;top: -2%">
        <el-row>
          <h2>{{ cultureDetail.name }}</h2>
        </el-row>
        <el-row>
          <p><strong>创建时间:</strong> {{ cultureDetail.createdAt }}</p>
        </el-row>
        <el-row>
          <p><strong>地点:</strong> {{ cultureDetail.location }}</p>
        </el-row>
        <el-row>
          <p><strong>描述:</strong></p>
          <div v-html="cultureDetail.description"></div>
        </el-row>
      </el-col>
    </el-row>
    <br>
    <el-row class="comment-section">
        <el-row style="text-align: center">
          <img alt="" src="@/assets/image/留言.png">
          <h2>
            发表评论
          </h2>
        </el-row>
        <br>
        <el-row>
          <el-input v-model="comment"
                    :rows="2"
                    placeholder="说点什么呢"
                    type="textarea">
          </el-input>
        </el-row>
        <br>
        <el-row>
          <el-button type="primary" @click="submitComment">提交评论</el-button>
        </el-row>
        <el-divider/>
        <div v-if="comments.length">
          <el-row v-for="(comment) in comments" :key="comment.id"
                  class="comment-item"
                  style="margin-top: 20px;padding: 10px;border-radius: 10px;background-color: #dcefff;"
                  type="flex">
            <div>
              <el-image :src="comment.imageUrl || avatar"
                        style="border-radius: 50%;width: 50px;height: 50px"></el-image>
            </div>
            <div style="margin-left: 10px;width: 90%">
              <div>{{ comment.username }}</div>
              <div style="word-wrap: break-word; /* 确保长单词或URL换行 */
                        white-space: normal; /* 允许文本换行 */
                        overflow-wrap: break-word; /* 确保长单词或URL换行 */
                        max-width: 100%; /* 确保内容区域有最大宽度 */
                        overflow: hidden; /* 隐藏溢出内容 */
                        text-overflow: ellipsis; /* 显示省略号 */">
                <strong v-html="comment.content"></strong>
              </div>
              <div class="reply" style="color: #949cb9">
                <small>{{ comment.createdAt }}</small>
                <small @click="addLike(comment.id,false)">
                  <img alt="" src="@/assets/image/赞.png" style="width: 20px;height: 20px">
                  <span>
                  {{ comment.likes }}
                  </span>
                </small>
                <small @click="addTread(comment.id,false)">
                  <img alt="" src="@/assets/image/踩.png" style="width: 20px;height: 20px">
                  <span>
                  {{ comment.tread }}
                  </span>
                </small>
                <small @click="reply(comment.id,comment.userId,comment.username)">
                  回复
                </small>
                <small @click="removeComments(comment.id,comment.content)">
                  删除
                </small>
              </div>
              <div v-if="comment.children.length"
                   style="background-color: aliceblue;padding: 10px;border-radius: 10px;">
                <div v-for="(childrenComment) in comment.children" :key="childrenComment.id">
                  <div style="padding: 5px">
                    <div style="display: flex">
                      <div>
                        <el-image :src="childrenComment.imageUrl || avatar"
                                  style="border-radius: 50%;width: 50px;height: 50px"></el-image>
                      </div>
                      <div style="margin-left: 10px;width: 90%">
                        <div style="display: flex">{{ childrenComment.username }}
                          <strong>回复</strong> <span style="color: #00afff">@{{ childrenComment.target }}</span>：
                          <div style="word-wrap: break-word; /* 确保长单词或URL换行 */
                        white-space: normal; /* 允许文本换行 */
                        overflow-wrap: break-word; /* 确保长单词或URL换行 */
                        max-width: 100%; /* 确保内容区域有最大宽度 */
                        overflow: hidden; /* 隐藏溢出内容 */
                        text-overflow: ellipsis; /* 显示省略号 */">
                            <strong v-html="childrenComment.content"></strong>
                          </div>
                        </div>
                        <div class="reply" style="color: #949cb9">
                          <small>{{ childrenComment.createdAt }}</small>
                          <small @click="addLike(childrenComment.id,true)">
                            <img alt="" src="@/assets/image/赞.png" style="width: 20px;height: 20px">
                            <span>
                            {{ childrenComment.likes }}
                            </span>
                          </small>
                          <small @click="addTread(childrenComment.id,true)">
                            <img alt="" src="@/assets/image/踩.png" style="width: 20px;height: 20px">
                            <span>
                            {{ childrenComment.tread }}
                            </span>
                          </small>
                          <small @click="reply(childrenComment.pid,childrenComment.userId,childrenComment.username)">
                            回复
                          </small>
                          <small
                              @click="removeComments(childrenComment.id,childrenComment.content)">
                            删除
                          </small>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-row>
        </div>
        <el-empty v-else description="快来发表评论吧"></el-empty>
        <div v-loading="loadingComment" class="loadMessage"
             @click="handleLoadComment">
          <img alt="" src="@/assets/image/加载.png">
          <span>加载更多...</span>
        </div>
    </el-row>
  </div>
</template>

<script>
import {
  getCommentsByCultureId,
  getCommentsMaxLikes,
  queryCultureById,
  removeComments,
  submitComment,
  updateLike,
  updateTread
} from "@/api/request/CultureCommunityRequest";

export default {
  name: "CultureInfoDetailView",
  data() {
    return {
      avatar: require('@/assets/image/no_image.png'),
      userInfo: {},
      id: this.$route.query.id,
      cultureDetail: {},
      comments: [],
      loading: true,
      comment: null,
      loadingComment: false,
      treadFlag: true,
      CommentsMaxLikes: {},
      queryParams: {
        currentPage: 1,
        pageSize: 5,
        CultureId: this.$route.query.id
      }
    };
  },
  methods: {
    removeComments(commentId, content) {
      if (!this.userInfo) {
        this.$message.warning('请先登录');
        return;
      }

      this.$confirm(`删除评论:${content}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeComments(commentId).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.msg);
            return;
          }

          this.getCommentsByCultureId()
          this.$message.success('评论删除成功');
        }).catch(error => {
          console.log(error)
        });
      }).catch(error => {
        console.log(error)
      });
    },
    addLike(id, isChild) {
      const comment = isChild
          ? this.comments.find(comment => comment.children.some(child => child.id === id)).children.find(child => child.id === id)
          : this.comments.find(comment => comment.id === id);

      const likes = comment.liked ? 1 : 0;

      updateLike({commentId: id, likes}).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }

        if (comment.liked) {
          comment.likes += 1;
        } else {
          comment.likes -= 1;
        }

        comment.liked = !comment.liked;
      }).catch(error => {
        console.log(error)
      });
    },
    addTread(id, isChild) {
      const comment = isChild
          ? this.comments.find(comment => comment.children.some(child => child.id === id)).children.find(child => child.id === id)
          : this.comments.find(comment => comment.id === id);

      const treader = comment.treader ? 1 : 0;

      updateTread({commentId: id, treader}).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }

        if (comment.treader) {
          comment.tread += 1;
        } else {
          comment.tread -= 1;
        }

        comment.treader = !comment.treader;
      }).catch(error => {
        console.log(error)
      });
    },
    reply(pid, userId, username) {
      if (!this.userInfo) {
        this.$message.warning('请先登录');
        return;
      }

      this.$prompt(`回复${username}`, '回复评论', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputErrorMessage: '评论不能为空'
      }).then(({value}) => {
        if (!value) {
          this.$message.warning('评论不能为空');
          return
        }
        submitComment({
          userId: this.userInfo.id,
          content: value,
          projectId: this.$route.query.id,
          pid: pid,
          target: username
        }).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.msg);
            return;
          }
          this.getCommentsByCultureId()
          this.$message.success('评论提交成功');
        }).catch(error => {
          console.log(error)
        });
      }).catch(error => {
        console.log(error)
      });
    },
    submitComment() {
      if (!this.userInfo) {
        this.$message.warning('请先登录');
        return;
      }

      if (!this.comment) {
        this.$message.warning('请输入评论内容');
        return;
      }

      submitComment({
        userId: this.userInfo.id,
        content: this.comment,
        projectId: this.$route.query.id,
      }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }

        this.comment = ''; // 清空输入框
        this.getCommentsByCultureId()
        this.$message.success('评论提交成功');
      }).catch(() => {
      });
    },
    getList() {
      queryCultureById(this.id).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }
        this.cultureDetail = res.data;
      }).catch(error => {
        console.log(error)
      }).finally(() => {
        this.loading = false;
      });
    },
    getCommentsMaxLikes() {
      getCommentsMaxLikes(this.$route.query.id).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }
        this.CommentsMaxLikes = res.data;
        console.log(this.CommentsMaxLikes)
      }).catch(error => {
        console.log(error)
      });
    },
    getCommentsByCultureId() {
      this.loadingComment = true;
      getCommentsByCultureId(this.queryParams).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }
        this.comments = res.data.list.map(comment => ({
          ...comment,
          liked: true, // 初始化点赞状态
          treader: true, // 初始化踩状态
          children: comment.children.map(child => ({
            ...child,
            liked: true, // 初始化点赞状态
            treader: true // 初始化踩状态
          }))
        }));
      }).catch(error => {
        console.log(error)
      }).finally(() => {
        this.loadingComment = false;
      });
    },
    handleLoadComment() {
      this.queryParams.pageSize += 5;
      this.getCommentsByCultureId()
    }
  },
  mounted() {
    this.getList();
    this.getCommentsByCultureId();
    this.getCommentsMaxLikes();
    this.userInfo = JSON.parse(localStorage.getItem('xm-user'));
  }
};
</script>

<style lang="scss" scoped>
.culture-theme {
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 10px;
}

.CultureInfoDetail {
  font-family: 'Arial', sans-serif;
  color: #333;

  .CultureInfoDetail-left {
    position: relative;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    padding: 20px;
    border-radius: 10px;
    transition: all 0.3s ease;
    background: url("@/assets/image/bj.png") no-repeat #ffffff;
    background-size: cover;
    text-align: center;

    h2 {
      margin-top: 0;
      color: #333;
      font-size: 24px;
      font-weight: bold;
    }

    p {
      margin: 10px 0;
      color: #666;
      font-size: 16px;
    }

    div {
      margin: 10px 0;
      color: #666;
      font-size: 16px;
    }

    .CultureInfoDetail-left-title {
      font-size: 20px;
      font-weight: 700;
      text-align: center;
      border-radius: 10px;
      box-shadow: 2px 2px 15px 0 #d5dceb;
      padding: 10px 0;
      align-items: center;
      margin: 0;
    }
  }

  .loading {
    padding: 20px;
    text-align: center;
    color: #999;
  }
}

.comment-section {
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background-color: white;
  padding: 20px;
  width: 93%;
  position: relative;
  margin: 0 auto;
}

.reply small {
  margin: 0 10px;
  vertical-align: middle;
  cursor: pointer;
}

.reply small:first-child {
  margin: 0;
}

.loadMessage {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  padding: 10px;
  background-color: #4483f5;
  border-radius: 10px;
  transition: all .5s;

  img {
    width: 20px;
  }
}

.loadMessage:hover {
  background-color: #4482f5;
  color: white;
}
</style>

